package com.healthySys.common.utils;

import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;

@Component
@RequiredArgsConstructor
public class UserContextUtil {

    private final StringRedisTemplate redisTemplate;

    /**
     * 获取全部在线用户
     */
    public Map<String, String> getALlSecurityContext() {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth == null) {
            return Collections.singletonMap("error", "没有任何在线用户");
        }
        LinkedHashMap<String, String> context = new LinkedHashMap<>();
        context.put("username", auth.getName());
        context.put("authorities", auth.getAuthorities().stream()
                .map(Object::toString)
                .collect(Collectors.joining(",")));
        context.put("authenticated", String.valueOf(auth.isAuthenticated()));
        return context;
    }

    /**
     * 获取当前在线用户名称
     */
    public String getCurrentUsername() {
        return SecurityContextHolder.getContext().getAuthentication().getName();
    }

    /**
     * 获取当前用户角色
     */
    public String getCurrentRole() {
        return SecurityContextHolder.getContext().getAuthentication().getAuthorities().stream()
                .map(Object::toString)
                .collect(Collectors.joining(","));
    }


    /**
     * 获取所有在线用户名称
     */
    public Set<String> getRedisContext() {
        return Optional.ofNullable(redisTemplate.keys("*"))
                .orElse(Collections.emptySet())
                .stream()
                .filter(key -> !key.startsWith("spring:")) // 过滤系统key
                .collect(Collectors.toSet());
    }
}
